package com.mt.mall.service.merchant.impl;

import com.mt.common.system.service.UserService;
import com.mt.mall.dao.merchant.ShopDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.mall.entity.merchant.Shop;
import com.mt.mall.service.merchant.ShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class ShopServiceBean extends BaseService implements ShopService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private ShopDao shopDao;

	@Resource
	private RedisTemplate<String, List<Shop>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	/**
	 * 根据分页参数查询店铺集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findShops(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindShops(pageDTO);
		List<Shop> shopDTOS = this.shopDao.findShops(pageDTO);
		Long totalCount = this.shopDao.findShopTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(shopDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部店铺集合
	 *
	 */
	@Override
	public List<Shop> findAllShops(){
		return this.shopDao.findAllShops();
	}

	/**
	 * 查询所有店铺集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<Shop> findAllShopsWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllShopsWithIdName();
		return this.shopDao.findAllShopsWithIdName();
	}

	/**
	 * 根据名称查询店铺集合(只提取ID 和 Name)
	 *
	 * @param shopName 名称
	 */
	@Override
	public List<Shop> findShopsWithIdNameByName(String shopName){
		//TODO:请在此校验参数的合法性
		this.validateFindShopsWithIdNameByName(shopName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:Shop_where_shopName_" + shopName);
		List<Shop> shops = new ArrayList<>();
		if (keys.isEmpty()) {
		shops = this.shopDao.findShopsWithIdNameByName(shopName);
		redisTemplate.opsForValue().set("searchData:Shop_where_shopName_" + shopName, shops, 30, TimeUnit.DAYS);
		} else {
		shops = redisTemplate.opsForValue().get("searchData:Shop_where_shopName_" + shopName);
		}
		return shops;
	}

	/**
	 * 根据ID查询指定的店铺(只提取ID 和 Name)
	 *
	 * @param shopId Id
	 */
	@Override
	public Shop findShopsWithIdNameById(Long shopId){
		//TODO:请在此校验参数的合法性
		this.validateFindShopsWithIdNameById(shopId);
		return this.shopDao.findShopsWithIdNameById(shopId);
	}

	/**
	 * 根据ID查询指定的店铺
	 *
	 * @param shopId Id
	 */
	@Override
	public Shop findShop(Long shopId){
		//TODO:请在此校验参数的合法性
		this.validateFindShop(shopId);
		return this.shopDao.findShop(shopId);
	}

	/**
	 * 根据ID查询指定的店铺(包含外键)
	 *
	 * @param shopId Id
	 */
	@Override
	public Shop findShopWithForeignName(Long shopId){
		//TODO:请在此校验参数的合法性
		this.validateFindShopWithForeignName(shopId);
		return this.shopDao.findShopWithForeignName(shopId);
	}
	/**
	 * 新增店铺
	 *
	 * @param shop 实体对象
	 */
	@Override
	public Shop saveShop(Shop shop){
		//TODO:请在此校验参数的合法性
		this.validateSaveShop(shop);
		//TODO:填充公共参数
		this.setSavePulicColumns(shop);
		Long rows = this.shopDao.saveShop(shop);
		if(rows != 1)
		{
			String error = "新增保存店铺出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}
		//店铺与user绑定
		this.shopDao.bindUser(shop.getUserId(),shop.getEid());
		return shop;
	}

	/**
	 * 更新店铺
	 *
	 * @param shop 实体对象
	 */
	@Override
	public Shop updateShop(Shop shop){
		//TODO:请在此校验参数的合法性
		this.validateUpdateShop(shop);
		Long rows = this.shopDao.updateShop(shop);
		if(rows != 1)
		{
			String error = "修改保存店铺出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return shop;
	}

	/**
	 * 根据ID删除店铺
	 *
	 * @param shopId ID
	 */
	@Override
	public void deleteShop(Long shopId){
		//TODO:请在此校验参数的合法性
		this.validateDeleteShop(shopId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(Shop.class, shopId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.shopDao.deleteShop(shopId);
		if(rows != 1){
			String error = "删除店铺出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}

	//TODO:---------------验证-------------------

	private void validateFindShops(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateShop()写法
	}

	private void validateFindShopsWithIdNameByName(String shopName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateShop()写法
	}


	private void validateFindAllShopsWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateShop()写法
	}

	private void validateFindShopsWithIdNameById(Long shopId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateShop()写法
	}

	private void validateFindShop(Long shopId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateShop()写法
	}

	private void validateFindShopWithForeignName(Long shopId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateShop()写法
	}

	private void validateSaveShop(Shop shop) {
	//不为空判断
	if (shop.getEid() != null || shop.getCreatorId() != null || shop.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateShop()写法
	}

	private void validateUpdateShop(Shop shop) {
	//不为空判断
	if (shop.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.shopDao.findShopTotalCount(PageDTO.create(Shop.FIELD_ID, shop.getEid())) == 0) {
	throw new BusinessException("修改的店铺 " + shop.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateShop()写法
	}

	private void validateDeleteShop(Long shopId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateShop()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
